#include "TestHelper.h"
#include <string.h>
#include <stdlib.h>

bool IsIPAddress(const char* pszStr, int iLength /* = -1 */)
{
    if (NULL != pszStr)
    {
        const int length = (iLength == -1 ? strlen(pszStr) : iLength);
        if (length > 15)
        {
            return false;
        }

        char sTmp[16] = { '\0' };
        char* fields[4] = { NULL, NULL, NULL, NULL };
        int iDotCount = 0;
        for (int i = 0; i < length && iDotCount < 4; i++)
        {
            if (pszStr[i] >= '0' && pszStr[i] <= '9')
            {
                sTmp[i] = pszStr[i];
                if (fields[iDotCount] == NULL)
                {
                    fields[iDotCount] = sTmp + i;
                }
            }
            else if (pszStr[i] == '.')
            {
                sTmp[i] = '\0';
                iDotCount++;
            }
            else
            {
                return false;
            }
        }

        if (iDotCount >= 4)
        {
            return false;
        }

        for (int i = 0; i < 4; i++)
        {
            const int fieldValue = atoi(fields[i]);
            if (fieldValue < 0 || fieldValue > 254)
            {
                return false;
            }

            if (fieldValue != 0 && fields[i][0] == '0')
            {
                return false;
            }

            if (fieldValue == 0 && (i == 0 || i == 4))
            {
                return false;
            }
        }

        return true;
    }

    return false;
}
